package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistsException;
import com.atguigu.gulimall.member.exception.UserNameExistsException;
import com.atguigu.gulimall.member.utils.HttpUtils;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import com.fasterxml.jackson.databind.util.BeanUtil;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.crypto.generators.BCrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelDao memberLevelDao;  //通过此Dao查取(默认)会员等级

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo memberRegistVo) throws PhoneExistsException,UserNameExistsException{
        MemberEntity memberEntity = new MemberEntity();

        //设置会员的等级id
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());

        //我们需要检查手机号和用户名是否唯一，只要有一个重复了就不行
        checkPhoneUnique(memberRegistVo.getPhone());
        checkUsernameUnique(memberRegistVo.getUserName());
        memberEntity.setMobile(memberRegistVo.getPhone());
        memberEntity.setUsername(memberRegistVo.getUserName());

        //密码从前端传递过来是明文传输，但存入数据库需要加密存储吗，                                                                                          memberEntity.setPassword(memberRegistVo.getPassword());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(memberRegistVo.getPassword());
        memberEntity.setPassword(encode);

        //其他的默认注册信息

        //保存用户的注册信息
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistsException{
        List<MemberEntity> mobiles = baseMapper.selectList(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(mobiles != null && mobiles.size() > 0){
            throw new PhoneExistsException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UserNameExistsException{
        List<MemberEntity> usernames = baseMapper.selectList(new QueryWrapper<MemberEntity>().eq("username", username));
        if(usernames != null && usernames.size() > 0){
            throw new UserNameExistsException();
        }
    }

    /**
     * 去数据库查询账号密码
     * @param memberLoginVo
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {
        memberLoginVo.getLoginAcct();
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", memberLoginVo.getLoginAcct()
        ).or().eq("mobile", memberLoginVo.getLoginAcct()));
        if(memberEntity == null){
            return null;
        }else {
            //从数据库拿到的加密的密码
            String password = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //用数据库的密码与用户输入的密码进行比对
            boolean matches = passwordEncoder.matches(memberLoginVo.getPassword(), password);
            if(matches){
                return memberEntity;
            }else {
                return null;
            }
        }

    }


    /**
     * 登陆的同时把原先的数据库会员信息(令牌信息)更新
     * @param socialUser
     * @return
     */
    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //社交登录，具有注册和登录合并逻辑
        String uid = socialUser.getUid();
        //1.判断当前社交用户是否已经登陆过系统（先不考虑那么复杂的情况，仅
        // 考虑这个用户之前就是用社交登录进入的谷粒商城，过了很长时间还想利用社交登录
        // 进入。不考虑这个用户捣乱1分钟前就是社交登录进入的，accessToken还没过期就又
        // 用社交登录进入一次）
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(memberEntity != null){      //说明这个用户已经通过社交登录，系统曾为他自动注册过会员
            //先更新之前过期的accessToken
            MemberEntity update = new MemberEntity();
            BeanUtils.copyProperties(memberEntity,update);
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            baseMapper.updateById(update);

            return memberEntity;//我觉得只需要返回一个MemberEntity对象即可，Controller判断是否为空，老师是返回的与数据库一致的数据
        }else {
            //说明是第一次登录，那就向数据库ums_member插入一条会员信息即可
            MemberEntity newMember = new MemberEntity();
            //查询当前社交用户的社交账号信息(昵称、性别等),可能因为网络的问题导致没有从微博拿到信息，但这也应该让用户自动注册进去，因此我们用try..catch
            Map<String,String> query = new HashMap<>();
            query.put("access_token",socialUser.getAccess_token());
            query.put("uid",socialUser.getUid());
            try{
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), query);
                if(response.getStatusLine().getStatusCode() == 200){    //查询成功
                    String string = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(string);   //因为微博给的实在是太多了，我们就先不转成Vo对象了，太麻烦，先转成阿里的Map对象
                    String nickName = jsonObject.getString("name");  //把人家微博的名字当做昵称存在数据库中
                    String gender = jsonObject.getString("gender"); //把人家用户的性别存入数据库中,这个gender是“m”或“f”，而ums_member数据库中需要存的是0或1
                    newMember.setNickname(nickName);
                    newMember.setGender("m".equals(gender)?1:0);
                    //你还可以从微博拿到很多其他信息，我就不在这继续重复一样的代码了。。。。。。。
                }
            }catch (Exception e){}

            newMember.setAccessToken(socialUser.getAccess_token());
            newMember.setExpiresIn(socialUser.getExpires_in());
            newMember.setSocialUid(socialUser.getUid());
            baseMapper.insert(newMember);
            return newMember;
        }
    }
}